<template>
	<view >
		<u-popup :show="value" @close="close" @open="open" round="18">
			<view class="choose-house-modal" >
				<!-- 顶部标题和关闭 -->
				<view class="modal-header">
					<text class="modal-title">请选择</text>
          <view class="modal-header-close">
					<u-icon name="close" size="22" color="#999" @click="close"></u-icon>
          </view>
				</view>
				
				<!-- <view class="modal-search">
				    <u-search :showAction="false" bgColor="#F4F4F4" placeholder="请输入房屋进行搜索" 
					v-model="keyword"></u-search>
				</view> -->
				
				<view class="modal-tip">
				<view class="choose-house-warning choose-house-warning-tip">
        <u-image :src="warning" width="42rpx" height="42rpx"></u-image>
        <text class="choose-house-warning-text">
          {{ singleSelect ? '注：请选择栋数或者单元' : '注：若您有多套房，请全部选择后再点击确定' }}
        </text>
      </view>
				</view>
				<!-- 三栏联动 -->
				<view class="house-list-3col">
					<!-- 区域 -->
					<scroll-view scroll-y class="house-col-left col-area">
						<view
             class="col-item-left"
							v-for="(area, aIdx) in areaList"
							:key="aIdx"
							:class="[
								'col-item',
								aIdx === activeArea ? 'active' : ''
							]"
							@click="selectArea(aIdx)"
						>
							<view v-if="aIdx === activeArea" class="mine-border"></view>
							<text>{{ area.name }}</text>
							<view
								v-if="getSelectedCountByArea(area) > 0"
								class="mine-badge"
							>{{ getSelectedCountByArea(area) }}</view>
						</view>
					</scroll-view>
					<!-- 楼栋 -->
					<scroll-view scroll-y class="house-col col-building">
						<view
							v-for="(building, bIdx) in safeBuildings"
							:key="bIdx"
							:class="['col-item', bIdx === activeBuilding ? 'active' : '']"
							@click="selectBuilding(bIdx)"
						>
							<text>{{ building.name }}</text>
							<view
								v-if="getSelectedCountByBuilding(building) > 0"
								class="mine-badge"
							>{{ getSelectedCountByBuilding(building) }}</view>
						</view>
					</scroll-view>
					<!-- 单元 -->
					<scroll-view scroll-y class="house-col house-col2 col-unit">
						<template v-if="activeArea >= 0 && activeBuilding >= 0">
							<view
								v-for="(unit, uIdx) in safeUnits"
								:key="uIdx"
								class="col-item unit-item"
              	@click="toggleUnit(safeAreaName, safeBuildingName, unit.name, unit.id)"
							>
								<text
									:class="['unit-no', isChecked(safeAreaName, safeBuildingName, unit.name, unit.id) ? 'checked' : '']"
								>
                {{ unit.name }}</text>
                <view class="checkbox-unit" >
								<u-checkbox
									:checked="isChecked(safeAreaName, safeBuildingName, unit.name, unit.id)"
									shape="square"
									activeColor="#3C75FA"
                
								/>
                <view class="checkbox-unit-checked"></view>
                </view>
      
							</view>
						</template>
						<template v-else>
              <view class="col-item" style="color:#bbb;">请先选择区域和楼栋</view>
						</template>
					</scroll-view>
				</view>
				<!-- 底部按钮 -->
				<view class="modal-footer">
					<button
						class="modal-footer-btn"
						:class="{ 'modal-footer-btn-disabled': !selectedUnits.length }"
						:disabled="!selectedUnits.length"
            @click="handleConfirm"
					>
          确定
						
					</button>
				</view>
        <view class="app-bottom-paddig"></view>
			</view>
		</u-popup>
	</view>
</template>
<script>
import warning from '@/static/warning.svg'
import {getAreaQuery,getHouseList} from '@/api'
export default {
  props: {
    value: {
      type: Boolean,
      default: false
    },
    communityId: {
      type: String,
      default: ''
    },
    // 是否单选模式，默认为false（多选）
    singleSelect: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      warning,
      keyword: '',
      areaList: [],
      activeArea: -1,
      activeBuilding: -1,
      selectedUnits: []
    }
  },
  computed: {
    safeBuildings() {
      if (this.activeArea < 0) return [];
      const area = this.areaList[this.activeArea];
      return area && area.buildings ? area.buildings : [];
    },
    safeUnits() {
      if (this.activeArea < 0 || this.activeBuilding < 0) return [];
      const area = this.areaList[this.activeArea];
      if (!area || !area.buildings) return [];
      const building = area.buildings[this.activeBuilding];
      return building && building.units ? building.units : [];
    },
    safeAreaName() {
      if (this.activeArea < 0) return '';
      const area = this.areaList[this.activeArea];
      return area ? area.name : '';
    },
    safeBuildingName() {
      if (this.activeArea < 0 || this.activeBuilding < 0) return '';
      const area = this.areaList[this.activeArea];
      if (!area || !area.buildings) return '';
      const building = area.buildings[this.activeBuilding];
      return building ? building.name : '';
    },
    mySelectedUnits() {
      return this.selectedUnits.map(key => {
        const { areaId, buildingId, unitId, areaName, buildingName, unitName } = this.parseUnitKey(key);
        
        return {
          areaId: areaId,              // 区域ID
          buildingId: buildingId,      // 楼栋ID
          unitId: unitId,              // 单元ID
          areaName: areaName,          // 区域名称
          buildingName: buildingName,  // 楼栋名称
          unitName: unitName,          // 单元名称
        };
      });
    }
  },
  watch: {
    areaList(newList) {
      if (this.activeArea >= newList.length) {
        this.activeArea = -1;
        this.activeBuilding = -1;
      }
      if (newList[this.activeArea]?.buildings && this.activeBuilding >= newList[this.activeArea].buildings.length) {
        this.activeBuilding = -1;
      }
    }
  },
  created() {
    this.getAreaQuery()
  },
  methods: {
    // 统一的 key 构造函数
    generateUnitKey(areaId, buildingId, unitId, areaName, buildingName, unitName) {
      return `${areaId}|${buildingId}|${unitId}|${areaName}|${buildingName}|${unitName}`;
    },
    // 统一的 key 解析函数
    parseUnitKey(key) {
      const parts = key.split('|');
      return {
        areaId: parts[0],
        buildingId: parts[1],
        unitId: parts[2],
        areaName: parts[3],
        buildingName: parts[4],
        unitName: parts[5]
      };
    },
    async getAreaQuery() {
      let data = await getAreaQuery({ communityId: this.communityId, pageNum: 1, pageSize: 1000, status: 1 });
      let areas = data.rows || [];

      // 处理数据结构：区域 -> 楼栋 -> 单元
      let areaList = areas.map(area => {
        let buildings = [];
        
        if (area.pmsBuilds && area.pmsBuilds.length > 0) {
          buildings = area.pmsBuilds.map(build => {
            let units = [];
            
            if (build.units && build.units.length > 0) {
              // 有单元，说明是3级结构
              units = build.units.map(unit => ({
                id: unit.id,
                name: unit.name
              }));
            } else {
              // 没有单元，说明是2级结构，创建一个虚拟单元
              units = [{
                id: build.id,
                name: build.name
              }];
            }
            
            return {
              id: build.id,
              name: build.name,
              units: units
            };
          });
        } else {
          // 没有楼栋，说明是1级结构，创建虚拟楼栋和单元
          buildings = [{
            id: area.areaId,
            name: area.name,
            units: [{
              id: area.areaId,
              name: area.name
            }]
          }];
        }
        
        return {
          id: area.areaId,
          name: area.name,
          buildings: buildings
        };
      });
      console.log(areaList,'areaList')
      this.areaList = areaList;
    },
    moveHandle(e){
      e.preventDefault();
      e.stopPropagation();
    },
    handleConfirm(){
      this.close();
    },
    open() {},
    close() {
      this.$emit('input', false)
      setTimeout(()=>{
        this.$emit("confirm",this.mySelectedUnits)
      },0)
    },
    selectArea(idx) {
      this.activeArea = idx;
      this.activeBuilding = -1;
    },
    selectBuilding(idx) {
      this.activeBuilding = idx;
    },
    isChecked(areaName, buildingName, unitName, unitId) {
      const key = this.generateUnitKey(
        this.areaList[this.activeArea]?.id || '',
        this.areaList[this.activeArea]?.buildings[this.activeBuilding]?.id || '',
        unitId,
        areaName,
        buildingName,
        unitName
      );
      return this.selectedUnits.includes(key);
    },
    toggleUnit(areaName, buildingName, unitName, unitId) {
      const key = this.generateUnitKey(
        this.areaList[this.activeArea]?.id || '',
        this.areaList[this.activeArea]?.buildings[this.activeBuilding]?.id || '',
        unitId,
        areaName,
        buildingName,
        unitName
      );
    
      const idx = this.selectedUnits.indexOf(key);
      if (idx > -1) {
        this.selectedUnits.splice(idx, 1);
      } else {
        // 如果是单选模式，先清空之前的选择
        if (this.singleSelect) {
          this.selectedUnits = [];
        }
        this.selectedUnits.push(key);
      }
    },
    getSelectedCountByArea(area) {
      if (!area || !area.buildings) return 0;
      let count = 0;
      area.buildings.forEach(building => {
        count += this.getSelectedCountByBuilding(building);
      });
      return count;
    },
    getSelectedCountByBuilding(building) {
      if (!building || !building.units) return 0;
      let count = 0;
      building.units.forEach(unit => {
        const key = this.generateUnitKey(
          this.areaList[this.activeArea]?.id || '',
          building.id,
          unit.id,
          this.areaList[this.activeArea]?.name || '',
          building.name,
          unit.name
        );
        if (this.selectedUnits.includes(key)) {
          count++;
        }
      });
      return count;
    }
  }
}
</script>

<style lang="scss" scoped>
.choose-house-modal {
  width: 100%;
	background: #fff;
	border-radius: 18rpx;
	padding: 29rpx 0 0rpx 0;
  height: 941rpx;
}
.modal-header {
  width: 100%;
	display: flex;
	justify-content: space-between;
	align-items: center;
  padding-right: 34rpx;
  justify-content: center;
  position: relative;
  color: rgba(51, 51, 51, 1);
   &-close{
      position: absolute;
      right: 30rpx;
     
    }
}
.modal-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #222;
}
.modal-search {
  margin-top: 29rpx;
	padding: 0rpx 30rpx  41rpx 30rpx ;
}
.modal-tip {
	display: flex;
	align-items: center;
	color: #FF9900;
	font-size: 24rpx;
  width: 100%;
  justify-content: center;
  padding:0 34rpx;
  display: flex;
  justify-content: flex-start;
}
.modal-tip-text {
	margin-left: 8rpx;
}
.house-list-3col {
  display: flex;
  width: 100%;
  height:673rpx;
  background: #f8f8f8;
  border-radius: 16rpx;
  margin: 0 0 0 0;
  box-sizing: border-box;
}
.house-col {
  flex: 2;
  overflow: hidden;
  height: 100%;
}
.house-col-left{
  width: 206rpx;
  height: 100%;
}
.col-area {
  border-top-left-radius: 16rpx;
  border-bottom-left-radius: 16rpx;
  background: #f5f7fa;
}
.col-building {
  background: #fff;
}
.col-unit {
  background: #fff;
  border-top-right-radius: 16rpx;
  border-bottom-right-radius: 16rpx;
}
.col-item {
  height: 88rpx;
  display: flex;
  align-items: center;
  padding: 0 32rpx;
  font-size: 32rpx;
  color: #222;
  cursor: pointer;
  position: relative;
}
.col-item.active {
  background: #fff;
  color: $uni-color-primary;
  font-weight: 600;
  position: relative;
}
.col-item-left{
  display: flex;
  align-items: center;
  position: relative;
}
.mine-border {
  position: absolute;
  left: 0;
  height: 28rpx;
  width: 6rpx;
  background: $uni-color-primary;
  border-radius: 1998rpx 1998rpx 1998rpx 1998rpx;
}
.mine-badge {
  background: rgba(242, 74, 74, 1);
  color: #fff;
  font-size: 22rpx;
  border-radius: 50%;
  width: 32rpx;
  height: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 8rpx;
  position: absolute;
  right: 7rpx;
}
.unit-item {
  justify-content: space-between;
}
.unit-no {
  font-size: 30rpx;
  color: #222;
}
.unit-no.checked {
  color: $uni-color-primary;
  font-weight: 600;
}
.modal-footer {
	display: flex;
	align-items: center;
	 box-shadow: 0 -2rpx 16rpx 0 rgba(0,0,0,0.1);
	justify-content: space-between;
  padding: 16rpx 40rpx 0 32rpx;
}
.modal-footer-share {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-right: 32rpx;
}
.modal-footer-share-text {
   font-weight: 400;
    font-size: 28rpx;
    color: #333333;
	margin-top: 8rpx;
}
.modal-footer-btn {
	flex: 1;
	height: 88rpx;
	background: $uni-color-primary;
	color: #fff;
	font-size: 32rpx;
	border-radius: 12rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-weight: 500;
	margin-left: 16rpx;
	border: none;
}
.modal-footer-btn-disabled {
  background: #E5E5EA !important;
  color: #999999 !important;
  border: none !important;
}
.choose-house-warning {
  color: #F9901B;
  font-size: 28rpx;
}
.choose-house-warning-tip {
  margin-bottom: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.choose-house-warning-text {
  margin-left: 8rpx;
}
.col-item {
  width: 100%;
  height: 112rpx;
}
.my-col-item {
  font-weight: 600;
}
.my-group-item {
  font-size: 28rpx;
  color: #333;
  padding-left: 8rpx;
  white-space: nowrap;
}
.checkbox-unit{
  width:24px;
  height: 20px;
  position: relative;
}
.checkbox-unit-checked{
  width:24px;
  height: 20px;
  position: absolute;
  top: 0;
  left: 0;
}
.house-col2{
  flex: 2 !important;
  .col-item{
    width: 100%;
    justify-content: space-around;
  }
}
</style>
